package com.sharding.transaction.demo.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sharding.transaction.demo.api.IOrderProviderService;
import com.sharding.transaction.demo.api.IStoreProviderService;
import com.sharding.transaction.demo.entity.Goods;
import com.sharding.transaction.demo.entity.Orders;
import com.sharding.transaction.demo.service.OrdersService;
import com.sharding.transaction.demo.vo.OrdersVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.annotation.Resource;
import javax.jms.Queue;
import javax.jms.Topic;
import java.util.Date;

@org.apache.dubbo.config.annotation.Service(protocol = "dubbo", version = "1.0.0", group = "sharding-tr")
public class OrderProviderServiceImpl implements IOrderProviderService {

    @Reference(version = "1.0.0", group = "sharding-tr", check = false, retries = 3, cluster = "")
    private IStoreProviderService storeProviderService;

    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Resource
    private Queue queue;
    @Resource
    private Topic topic;

    @Autowired
    private OrdersService ordersService;

    @Override
    public Orders takeOrderSuc(Long userId, Long goodsId, Integer store) {
        Goods goods = storeProviderService.getById(goodsId);
        Orders orders = new Orders();
        orders.setGoodId(goodsId);
        orders.setGoodsName(goods.getName());
        orders.setUserId(userId);
        orders.setCreateTime(new Date());
        ordersService.save(orders);

        this.jmsMessagingTemplate.convertAndSend(this.queue, "下单成功 queue");
        this.jmsMessagingTemplate.convertAndSend(this.topic, "下单成功 topic");

        // 下单成功后通过mq通知给另一个服务扣款
//        if(storeProviderService.deductionStoreSuc(store, goodsId) > 0){
//            return orders;
//        }

        throw new RuntimeException("order provider -:下单失败！！！！");
    }

    @Override
    public Orders takeOrderFail(Long userId, Long goodsId, Integer store) {
        return null;
    }

    @Override
    public IPage<Orders> orders(Integer pageSize, Integer pageNumber, OrdersVo orders) {
        Page<Orders> page = new Page<>(pageNumber, pageSize);
        page.setOptimizeCountSql(false);
        page.setSearchCount(false);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getCreateTime);
        if(orders != null){
            if(orders.getCreateTimeStart() != null){
                queryWrapper.between(Orders::getCreateTime, orders.getCreateTimeStart(), orders.getCreateTimeEnd());
            }
        }
        return ordersService.page(page, queryWrapper);
    }
}
